package service

import (
	"context"
	"errors"
	"gitee.com/kaylee595/gkaylee/kerr"
	"gitee.com/kaylee595/wuaipojieCheck/pkg/wuaipojie"
	"gitee.com/kaylee595/yesCaptcha"
	"gitee.com/kaylee595/yesCaptcha/taskType/recaptchaV2"
	"time"
)

type Checker struct {
	Wuai         *wuaipojie.Client
	YesCaptcha   *yesCaptcha.Client
	WuaiUsername string
	WuaiPassword string
}

func (c *Checker) Do(ctx context.Context) error {
	var logged bool
	var verifyWaf bool
check:
	err := c.Wuai.Check(ctx)
	if err == nil {
		return nil
	}
	if errors.Is(err, wuaipojie.ErrNeedLogin) {
		if logged {
			return kerr.WrapTraceStack(err)
		}
		// 提示没登录就登录一下
		logged = true
		recaptchaResponse, err := c.getGRecaptchaResponse(ctx)
		if err != nil {
			return kerr.WrapTraceStack(err)
		}
		err = c.Wuai.Login(ctx, &wuaipojie.ReqLogin{
			Username:           c.WuaiUsername,
			Password:           c.WuaiPassword,
			GRecaptchaResponse: recaptchaResponse,
		})
		if err != nil {
			return kerr.WrapTraceStack(err)
		}
		goto check
	} else if e := new(wuaipojie.ErrNeedVerifyWaf); errors.As(err, &e) {
		if verifyWaf {
			return kerr.WrapTraceStack(err)
		}
		// 需要过一下验证
		verifyWaf = true
		payload, err := e.GeneratePayload()
		if err != nil {
			return kerr.WrapTraceStack(err)
		}
		err = c.Wuai.WafZWVerify(ctx, payload)
		if err != nil {
			return kerr.WrapTraceStack(err)
		}
		goto check
	}
	return kerr.WrapTraceStack(err)
}

func (c *Checker) getGRecaptchaResponse(ctx context.Context) (string, error) {
	// 创建任务
	respCreateTask, err := c.YesCaptcha.CreateTaskRecaptchaV2(ctx, recaptchaV2.Task{
		Type:       recaptchaV2.TypeNoCaptchaTaskProxyless,
		WebsiteURL: "https://www.52pojie.cn/member.php?mod=logging&action=login",
		WebsiteKey: "6LftSMEUAAAAANe9O4IJt4lDNV2naDxJwOu88w5o",
	})
	if err != nil {
		return "", kerr.WrapTraceStack(err)
	}
	ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
	defer cancel()
	// 获取任务结果
	getTaskResult, err := yesCaptcha.AwaitGetTaskResult(ctx, func() (*yesCaptcha.RespGetTaskResult[recaptchaV2.Solution], error) {
		return c.YesCaptcha.GetTaskResultRecaptchaV2(ctx, respCreateTask.TaskId)
	})
	if err != nil {
		return "", kerr.WrapTraceStack(err)
	}
	return getTaskResult.Solution.GRecaptchaResponse, nil
}
